package com.hh.hibernateplug.service.impl;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hh.baseframework.util.Convert;
import com.hh.hibernate.dao.inf.ILoginUserUtilService;
import com.hh.usersystem.bean.usersystem.HhXtYh;
import com.hh.usersystem.bean.usersystem.Organization;
import com.hh.usersystem.service.impl.UserService;
import com.hh.workflow.mode.User;
import com.opensymphony.xwork2.ActionContext;

@Service
public class LoginUserUtilServiceImpl implements ILoginUserUtilService,
		com.hh.workflow.service.inf.IUserService {
	@Autowired
	private UserService userService;

	public String findLoginUserId() {
		Object object = ActionContext.getContext().getSession()
				.get("loginuser");
		if (object != null) {
			HhXtYh hhXtYh = (HhXtYh) object;
			return hhXtYh.getId();
		}
		return null;
	}

	public String findLoginUserOrgId() {
		Object object = ActionContext.getContext().getSession().get("currOrg");
		if (object != null && !(object instanceof ArrayList)) {
			Organization organization = (Organization) object;
			return organization.getId();
		} else {
			return null;
		}
	}

	public User findUserById(String userId) {
		User user = new User();
		HhXtYh hhXtYh = userService.findObjectById2(userId);
		try {
			if (hhXtYh == null) {
				return user;
			}
			BeanUtils.copyProperties(user, hhXtYh);
			return user;
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		return null;
	}

	public User findLoginUser() {
		User user = new User();
		Object object = ActionContext.getContext().getSession()
				.get("loginuser");
		if (object != null) {
			HhXtYh hhXtYh = (HhXtYh) object;
			try {
				if (hhXtYh == null) {
					return user;
				}
				BeanUtils.copyProperties(user, hhXtYh);
				return user;
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}
		}
		return user;
	}

	public List<User> findUserListByIdList(List<String> userIdList) {
		String[] idStrings = new String[userIdList.size()];
		for (int i = 0; i < userIdList.size(); i++) {
			idStrings[i] = userIdList.get(i);
		}
		List<HhXtYh> hhXtYhs = userService.queryListByIds(idStrings);
		List<User> userList = new ArrayList<User>();
		for (HhXtYh hhXtYh : hhXtYhs) {
			User user = new User();
			try {
				BeanUtils.copyProperties(user, hhXtYh);
				userList.add(user);
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}
		}
		return userList;
	}
}
